package schoolsource.command;

import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import schoolsource.config.ConfigurationItems;
import schoolsource.gui.FormFields;
import schoolsource.gui.FormParser;
import schoolsource.model.ClassContainer;
import schoolsource.model.ContactContainer;
import schoolsource.model.GradeContainer;
import schoolsource.model.HomeworkContainer;
import schoolsource.model.MessageContainer;
import schoolsource.model.PairedUserContainer;
import schoolsource.model.PasswordItem;
import schoolsource.model.SubmissionContainer;
import schoolsource.model.UserContainer;
import schoolsource.security.SecurityAuthorizer;
import schoolsource.security.SecurityToken;
import schoolsource.sql.SchoolDBSQL;
import schoolsource.util.SchoolLogger;

/**
 * 
 * @author Steven Steele Copyright 2003
 * 
 * Manages all student and parent accesses.
 */
public class StudentParentAccessCMD extends HttpServlet {

	/**
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public void doPost(HttpServletRequest input, HttpServletResponse response)
			throws ServletException, IOException {

		SchoolLogger.logger
				.log(Level.INFO,
						"//////////////////////////////////////////////////////////////");

		SecurityToken st = null;
		boolean parent;
		String parentName = input.getParameter(FormFields.PARENTID);
		if (parentName != null && !"".equals(parentName)) {
			SchoolLogger.logger.log(Level.INFO, "parent is logging in ");
			parent = true;
		} else {
			SchoolLogger.logger.log(Level.INFO, "student is logging in");
			parent = false;
		}

		// Set up request dispatcher to display the next page.
		RequestDispatcher disp;
		ServletContext sc = getServletContext();

		Enumeration e = input.getParameterNames();
		String s;
		SchoolLogger.logger.log(Level.INFO, "List parameter values");
		while (e.hasMoreElements()) {
			s = (String) e.nextElement();
			SchoolLogger.logger.log(Level.INFO, s + ":  "
					+ input.getParameter(s));
		}

		String token = null;
		String link = input.getParameter(FormFields.BUTTONCLICKED);
		if (link == null) {
			link = input.getParameter(FormFields.LINKCLICKED);
		}
		String current = input.getParameter(FormFields.CURRENT);
		String param = input.getParameter(FormFields.PARAMETER);
		String userType = (String) input.getParameter(FormFields.USRTYPE);
		String schoolName = (String) input.getParameter(FormFields.SCHOOLNAME);
		input.setAttribute(FormFields.SCHOOLNAME, schoolName);
		input.setAttribute(FormFields.USRTYPE, userType);

		// Validate token. If not valid, send back the login page with
		// the appropriate message
		if ((token = input.getParameter(FormFields.TOKEN)) != null) {
			if ((st = SecurityAuthorizer.validateToken(token, 'S')) != null) {
				// put the Token in the request so the jsp can retrieve it
				input.setAttribute(FormFields.SESSION, st);

				parent = Boolean.valueOf(
						(String) st.getValue(FormFields.ISPARENT))
						.booleanValue();

				SchoolLogger.logger.log(Level.INFO, "valid token");

				// Determine which page the user was on (by the 'CURRENT'
				// parameter),
				// determine what the user did (BUTTONCLICKED), and get the
				// parameter
				// (PARAMETER)

				// If the user clicked logout, then dispose of the token and
				// return the
				// user to the login page
				if (FormFields.LOGOUT.equals(link)) {
					SchoolLogger.logger.log(Level.INFO, "Logged out 1");

					// De-allocate the session to free up memory
					SecurityAuthorizer.removeToken(st.toString());
					input.setAttribute("message", "User logged out.");
					disp = sc.getRequestDispatcher("/jsp/Login.jsp");
				} else if (current.equals(FormFields.CLASSINFO)) {
					// If the user clicked refresh, then reload all info and
					// redisplay the
					// page the user was on
					// This should be improved to refresh all pages - as it is
					// now, anything
					// in the view frame is lost.
					if (("Refresh".equals(link))) {
						int classnum = (new Integer((String) st
								.getValue(FormFields.CLASSNUM))).intValue();
						ClassContainer classC[] = (ClassContainer[]) st
								.getValue("classContainer");
						PairedUserContainer studentContainer = (PairedUserContainer) st
								.getValue("studentContainer");
						if (classnum == -2)
							getTodaysPage(studentContainer, st, parent);
						else if (classnum != -1)
							getClassPage(classC[classnum], studentContainer,
									st, parent);
						disp = sc
								.getRequestDispatcher("/jsp/StudentClassInfo.jsp");
					}
					// If the user clicked a class, load and display informaiton
					// for the new
					// class
					else if (FormFields.CLASSINFO.equals(link)) {
						int classnum = new Integer(param).intValue();
						ClassContainer classC[] = (ClassContainer[]) st
								.getValue("classContainer");
						st.putValue(FormFields.CLASSNUM, param);
						PairedUserContainer studentContainer = (PairedUserContainer) st
								.getValue("studentContainer");
						if (classnum == -2)
							getTodaysPage(studentContainer, st, parent);
						else
							getClassPage(classC[classnum], studentContainer,
									st, parent);
						disp = sc
								.getRequestDispatcher("/jsp/StudentClassInfo.jsp");
					}
					// Unrecognized link - load the main page.
					else {
						disp = sc
								.getRequestDispatcher("/jsp/StudentClassInfo.jsp");
					}
				}
				// If the user elected to work with a mail or homework
				else if (current.equals(FormFields.SUBFRAME)) {
					SchoolLogger.logger.log(Level.INFO, "current == SUBFRAME");
					st.putValue(FormFields.CLASSNUM, input
							.getParameter(FormFields.CLASSNUM));
					// If the user clicked an email, then display it
					if (FormFields.MAILLINK.equals(link)) {
						st.putValue(FormFields.MAILNUM, param);
						int mailnum = (new Integer((String) st
								.getValue(FormFields.MAILNUM))).intValue();
						// The following should never be -1
						if (mailnum != -1) {
							ContactContainer cc = ((ContactContainer[]) st
									.getValue("communicationContainer"))[mailnum];
							cc.getHidden().setValue("TRUE");
							SchoolDBSQL.getSchoolDBSQL(schoolName).save(cc);
						}
						disp = sc.getRequestDispatcher("/jsp/MailForm.jsp");
					} else if ("Submit Homework".equals(link)) {
						// save homework before parsing attachment so we can get
						// the unique hw id to use as the save folder if there
						// are any attachments
						if (!"".equals(input
								.getParameter(SchoolDBSQL.ATTFILENAME))) {// +
																			// ".filename")))
																			// {
							String homeworkID = input
									.getParameter(SchoolDBSQL.HWASSIGNEDID);
							HomeworkContainer homeworkContainer = HomeworkContainer
									.getHomeworkContainer(
											homeworkID,
											((String) st
													.getValue(FormFields.SCHOOLNAME)));
							PairedUserContainer user = (PairedUserContainer) st
									.getValue("studentContainer");
							SchoolLogger.logger.log(Level.INFO, "Submission");
							// if (((Boolean)
							// (homeworkContainer.getSubmissionsAllowed().getObject())).booleanValue())
							// {
							if (SubmissionContainer.getSubmissionContainer(
									homeworkContainer.getClassID().toString(),
									homeworkID,
									user.getAssignedID().toString(),
									((String) st
											.getValue(FormFields.SCHOOLNAME)))
									.getUpdateAllowed().booleanValue()) {
								try {
									FormParser
											.updateSubmission(
													input,
													homeworkContainer,
													user,
													((String) st
															.getValue(FormFields.SCHOOLNAME))
															+ ConfigurationItems.PATHSEPARATOR
															+ FormFields.HOMEWORKATTACHMENT,
													st
															.getValue(
																	FormFields.SCHOOLNAME)
															.toString());
									st.putValue("displayMessage",
											"Submission saved");
								} catch (IOException ioe) {
									st
											.putValue(
													"displayMessage",
													"An error occurred while trying to save your submission. Please try again later.");
								}
							} else {
								SchoolLogger.logger
										.log(
												Level.SEVERE,
												"An attempt to submit occurred when submissions were disabled! User assigned ID: "
														+ user.getAssignedID()
														+ "  School: "
														+ st
																.getValue(FormFields.SCHOOLNAME));
							}

						} else {
							st.putValue("displayMessage",
									"No submission received");
						}
						disp = sc.getRequestDispatcher("/jsp/view.jsp");
					}
					// If the user elected to delete mail, then delete it.
					else if (FormFields.DELMAIL.equals(link)) {
						int mailnum = (new Integer((String) st
								.getValue(FormFields.MAILNUM))).intValue();
						ContactContainer cc = ((ContactContainer[]) st
								.getValue("communicationContainer"))[mailnum];
						SchoolDBSQL.getSchoolDBSQL(schoolName)
								.moveContactToDeleted(cc);
						st.putValue("displayMessage", "Message Deleted");
						disp = sc.getRequestDispatcher("/jsp/view.jsp");
					}
					// If the user elected to reply to a mail, then display the
					// mail form.
					// The jsp will take care of pre-populating the fields.
					else if (FormFields.REPLY.equals(link)) {
						st.putValue(FormFields.MAILNUM, input
								.getParameter(FormFields.MAILNUM));
						disp = sc.getRequestDispatcher("/jsp/MailForm.jsp");
					}
					// If the user elected to view a homework, then display it.
					else if (FormFields.HWLINK.equals(link)) {
						st.putValue(FormFields.HWNUM, param);
						disp = sc.getRequestDispatcher("/jsp/HomeworkForm.jsp");
					}
					// i don't think this is correct.
					// else if (FormFields.PRINTLINK.equals(link)) {
					// disp = sc.getRequestDispatcher("/PasswordForm.jsp");
					// }
					// If the user elected to change his or her password, then
					// display
					// the password form.
					else if (FormFields.CHANGEPASSWORD.equals(link)) {
						disp = sc.getRequestDispatcher("/jsp/PasswordForm.jsp");
					} else if (FormFields.PROGRESSLINK.equals(link)) {
						int classnum = (new Integer((String) st
								.getValue(FormFields.CLASSNUM))).intValue();
						ClassContainer classContainer[] = (ClassContainer[]) st
								.getValue("classContainer");
						String teacherID = SchoolDBSQL.getSchoolDBSQL(
								schoolName).getClassTeacherID(
								classContainer[classnum].getClassAssignedID())
								.toString();
						PairedUserContainer studentContainer = (PairedUserContainer) st
								.getValue("studentContainer");
						String studentID = studentContainer.getStudentID()
								.toString();
						UserContainer teacherContainer = UserContainer
								.getUserContainer(teacherID, schoolName);
						HomeworkContainer homeworkContainer[] = SchoolDBSQL
								.getSchoolDBSQL(schoolName)
								.loadStudentClassHomework(
										classContainer[classnum]
												.getClassAssignedID());

						st.putValue("studentProgress", studentContainer);
						st.putValue("teacherContainer", teacherContainer);
						st.putValue("homeworkContainer", homeworkContainer);
						disp = sc
								.getRequestDispatcher("/jsp/ProgressReport.jsp");

					}
					// If the user elected to save a password change, then
					// validate
					// the change request and change it or display an error as
					// appropriate.
					else if ("Change Password".equals(link)) {
						SchoolLogger.logger.log(Level.INFO,
								"current == Change Password");
						// if current password is valid, then
						PairedUserContainer user = (PairedUserContainer) st
								.getValue("studentContainer");
						String oldPIParam = input
								.getParameter("CURRENTPASSWORD");
						PasswordItem oldPI = null;
						PasswordItem newPI = null;
						if (parent) {
							oldPI = new PasswordItem(SchoolDBSQL.USRPASSWORD,
									oldPIParam, true);
							newPI = new PasswordItem(SchoolDBSQL.USRPASSWORD,
									(String) null, true);
						} else {
							oldPI = new PasswordItem(SchoolDBSQL.USRPASSWORD,
									oldPIParam, true);
							newPI = new PasswordItem(SchoolDBSQL.USRPASSWORD,
									(String) null, true);
						}
						FormParser.getNewPassword(input, newPI);

						if (SecurityAuthorizer.isValidLogin(user
								.getAssignedID().toString(), oldPIParam,
								schoolName)) {
							if (newPI.getObject() == null) {
								st
										.putValue(
												"displayMessage",
												"The first new password you entered did not match the second. Your password has not been changed.");
								// disp =
								// sc.getRequestDispatcher("/StudentClassInfo.jsp");
								// disp = sc.getRequestDispatcher("/view.jsp");
								disp = sc
										.getRequestDispatcher("/jsp/PasswordForm.jsp");
							} else {
								SchoolDBSQL.getSchoolDBSQL(schoolName)
										.changeUserPassword(
												user.getAssignedID(), oldPI,
												newPI);
								st.putValue("displayMessage",
										"Password changed");
								// disp =
								// sc.getRequestDispatcher("/StudentClassInfo.jsp");
								if ("TRUE".equalsIgnoreCase(input
										.getParameter(FormFields.PSWDCHGREQ))) {
									user.getPasswordChangeRequired().setValue(
											"FALSE");
									disp = sc
											.getRequestDispatcher("/jsp/StudentClassInfo.jsp");
								} else {
									disp = sc
											.getRequestDispatcher("/jsp/view.jsp");
								}
							}
						} else {
							st.putValue("displayMessage", "Password incorrect");
							// disp =
							// sc.getRequestDispatcher("/StudentClassInfo.jsp");
							// disp = sc.getRequestDispatcher("/view.jsp");
							disp = sc
									.getRequestDispatcher("/jsp/PasswordForm.jsp");
						}
					}
					// If the user elected to send an email, send it
					else if ("Send".equals(link)) {
						SchoolLogger.logger.log(Level.INFO, "current == Send");

						// TODO make sure this always needs to be a new
						// container
						// MessageContainer mc =
						// MessageContainer.getMessageContainer("-1",
						// st.getValue(FormFields.SCHOOLNAME).toString());
						MessageContainer mc = MessageContainer
								.getMessageContainer("-1", schoolName);
						FormParser.updateMessage(input, mc);
						// SchoolDBSQL.getSchoolDBSQL((String)
						// st.getValue(FormFields.SCHOOLNAME)).save(mc);
						SchoolDBSQL.getSchoolDBSQL(schoolName).save(mc);
						// ContactContainer cc[] =
						// FormParser.createContacts(input, mc,
						// st.getValue(FormFields.SCHOOLNAME).toString());
						ContactContainer cc[] = FormParser.createContacts(
								input, mc, schoolName);
						for (int i = 0; i < cc.length; i++) {
							// SchoolDBSQL.getSchoolDBSQL((String)
							// st.getValue(FormFields.SCHOOLNAME)).save(cc[i]);
							SchoolDBSQL.getSchoolDBSQL(schoolName).save(cc[i]);
						}
						st.putValue("displayMessage", "Message Sent");
						// disp =
						// sc.getRequestDispatcher("/StudentClassInfo.jsp");
						disp = sc.getRequestDispatcher("/jsp/view.jsp");

					}
					// If the user elected to cancel sending an email or
					// homework, then
					// return to the main page.
					else if ("Cancel".equals(link)) {
						current = input.getParameter(FormFields.CURRENT);
						// disp =
						// sc.getRequestDispatcher("/StudentClassInfo.jsp");
						disp = sc.getRequestDispatcher("/jsp/view.jsp");
					}
					// unknown link click - default to the login page
					else {
						SchoolLogger.logger.log(Level.WARNING,
								"linkclicked was not recognized");
						SchoolLogger.logger.log(Level.INFO, "link: " + link);
						// input.setAttribute(FormFields.SCHOOLNAME,
						// schoolName);
						// input.setAttribute(FormFields.USRTYPE, userType);
						disp = sc.getRequestDispatcher("/jsp/Login.jsp");
					}
				}
				// Default to the login page
				else {
					disp = sc.getRequestDispatcher("/jsp/Login.jsp");
				}
			}
			// If the user elected to log out,then dispose of the token and
			// display the
			// student/parent login page
			else if (FormFields.LOGOUT.equals(link)) {
				SchoolLogger.logger.log(Level.INFO, "Logged out 2");

				// De-allocate the session to free up memory
				if (st != null) {
					SecurityAuthorizer.removeToken(st.toString());
				}
				input.setAttribute("message", "User logged out.");
				disp = sc.getRequestDispatcher("/jsp/Login.jsp");
			} else {

				input.setAttribute("message",
						"Your login has expired. Please log in again");

				Enumeration attrList = input.getParameterNames();
				String attrName;
				while (attrList.hasMoreElements()) {
					attrName = (String) attrList.nextElement();
					input.setAttribute(attrName, input.getParameter(attrName));
				}
				// input.setAttribute(FormFields.SCHOOLNAME, schoolName);
				// input.setAttribute(FormFields.USRTYPE, userType);
				disp = sc.getRequestDispatcher("/jsp/Login.jsp");
			}
		}
		// If the token was invalid or did not exist, try logging in user
		// via student username/parent username/password.
		else if ((parent
				// && input.getParameter(FormFields.PARENTID) != null
				&& parentName != null
				&& input.getParameter(FormFields.STUDENTID) != null && input
				.getParameter(SchoolDBSQL.USRPASSWORD) != null)
				|| (!parent && input.getParameter(FormFields.STUDENTID) != null && input
						.getParameter(SchoolDBSQL.USRPASSWORD) != null)) {
			if ((parent && SecurityAuthorizer.isValidParentLogin(input
					.getParameter(FormFields.PARENTID), input
					.getParameter(FormFields.STUDENTID), input
					.getParameter(SchoolDBSQL.USRPASSWORD), schoolName))
					|| (!parent && SecurityAuthorizer.isValidLogin(input
							.getParameter(FormFields.STUDENTID), input
							.getParameter(SchoolDBSQL.USRPASSWORD),
							SchoolDBSQL.STUDENT, schoolName))) {
				st = SecurityAuthorizer.generateToken();
				// put the Token in the request so the jsp can retrieve it
				input.setAttribute(FormFields.SESSION, st);

				st.putValue(FormFields.TOKEN, st.toString());
				st.putValue(FormFields.USRTYPE, new Character('S'));

				// Add school name here
				// TODO get the school name from the input
				st.putValue(FormFields.SCHOOLNAME, schoolName);

				// TODO get rid of the following if-else and all uses of this
				// 'parent' value - use the container value instead
				if (parent) {
					st.putValue(FormFields.ISPARENT, "true");
				} else {
					st.putValue(FormFields.ISPARENT, null);
				}

				// All of the individual query method calls should be moved into
				// a single method in SchoolDBSQL
				// and that method can be called from here. It should take in
				// the session and return
				// either nothing or a boolean indicating success or failure
				PairedUserContainer user;
				if (parent) {
					user = PairedUserContainer.getPairedContainer(SchoolDBSQL
							.getSchoolDBSQL(schoolName).getAssignedID(
									// (String)
									// st.getValue(FormFields.SCHOOLNAME)).getAssignedID(
									input.getParameter(FormFields.PARENTID),
									SchoolDBSQL.PARENT),
					// st.getValue(FormFields.SCHOOLNAME).toString());
							schoolName);
					user.getStudentID().setValue(
							SchoolDBSQL.getSchoolDBSQL(
							// (String)
							// st.getValue(FormFields.SCHOOLNAME)).getAssignedID(
									schoolName).getAssignedID(
									input.getParameter(FormFields.STUDENTID),
									SchoolDBSQL.STUDENT));
				} else {
					user = PairedUserContainer.getPairedContainer(SchoolDBSQL
							.getSchoolDBSQL(
							// (String)
							// st.getValue(FormFields.SCHOOLNAME)).getAssignedID(
									schoolName).getAssignedID(
									input.getParameter(FormFields.STUDENTID),
									SchoolDBSQL.STUDENT),
					// st.getValue(FormFields.SCHOOLNAME).toString());
							schoolName);
				}

				user.getFailures().setValue("0");

				// SchoolDBSQL.getSchoolDBSQL((String)
				// st.getValue(FormFields.SCHOOLNAME)).save(user);
				SchoolDBSQL.getSchoolDBSQL(schoolName).save(user);

				st.putValue("studentContainer", user);

				// Get classes and teacher info
				// The two arrays are synchronized so that the ith entry in one
				// corresponds to
				// the ith entry in the other
				// This is inefficient, since we may be storing (and querying)
				// the same sender's
				// information more than once
				ClassContainer studentClasses[] = SchoolDBSQL.getSchoolDBSQL(
				// (String)
				// st.getValue(FormFields.SCHOOLNAME)).loadStudentClasses(
						schoolName).loadStudentClasses(user.getIDForClasses());
				UserContainer studentClassTeachers[] = new UserContainer[studentClasses.length];
				for (int i = 0; i < studentClasses.length; i++) {
					studentClassTeachers[i] = UserContainer.getUserContainer(
							SchoolDBSQL
									// .getSchoolDBSQL((String)
									// st.getValue(FormFields.SCHOOLNAME))
									.getSchoolDBSQL(schoolName)
									.getClassTeacherID(
											studentClasses[i]
													.getClassAssignedID())
									.toString(),
							// st.getValue(FormFields.SCHOOLNAME).toString());
							schoolName);
				}
				st.putValue("classContainer", studentClasses);
				st.putValue("studentClassTeacher", studentClassTeachers);

				SchoolDBSQL.getSchoolDBSQL(
				// (String) st.getValue(FormFields.SCHOOLNAME)).resetUser(
						schoolName).resetUser(user.getAssignedID());

				PairedUserContainer studentContainer = (PairedUserContainer) st
						.getValue("studentContainer");
				// If the student has classes assigned, default to 0 and load
				// that page.
				// Otherwise, set to -1 to indicate there are no classes
				getTodaysPage(studentContainer, st, parent);

				if (studentClasses.length != 0) {
					st.putValue(FormFields.CLASSNUM, "-2");
				} else {
					st.putValue(FormFields.CLASSNUM, "-1");
				}
				if (studentContainer.getPasswordChangeRequired().toString()
						.equalsIgnoreCase("TRUE")) {
					st.putValue("displayMessage",
							"A password change is required for your user ID.");
					disp = sc.getRequestDispatcher("/jsp/PasswordForm.jsp");
				} else {
					disp = sc.getRequestDispatcher("/jsp/StudentClassInfo.jsp");
				}
			} else {
				SchoolLogger.logger.log(Level.WARNING,
						"Invalid username/password");
				input
						.setAttribute("message",
								"The username/password you entered could not be validated.");
				// input.setAttribute(FormFields.SCHOOLNAME, schoolName);
				// input.setAttribute(FormFields.USRTYPE, userType);
				disp = sc.getRequestDispatcher("/jsp/Login.jsp");
			}
		} else {
			input.setAttribute("message", null);
			// input.setAttribute(FormFields.SCHOOLNAME, schoolName);
			// input.setAttribute(FormFields.USRTYPE, userType);
			disp = sc.getRequestDispatcher("/jsp/Login.jsp");
		}

		// disp.forward(input, response);
		response.setContentType("text/html; charset=ISO-8859-2");
		System.out.println("disp: " + disp.toString());
		disp.include(input, response);
	}

	/**
	 * Forwards all calls to doPost
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public void doGet(HttpServletRequest input, HttpServletResponse response)
			throws ServletException, IOException {

		SchoolLogger.logger
				.log(Level.INFO,
						"//////////////////////////////////////////////////////////////");
		doPost(input, response);

	}

	/**
	 * Loads all mail and homework for a class.
	 * 
	 * @param cc
	 *            The class for which information is to be loaded.
	 * @param sc
	 *            The user container for which information is to be loaded.
	 * @param st
	 *            The token where information is to be stored.
	 * @param parent
	 *            Indicates whether the user is a parent (if not, then the user
	 *            is a student)
	 */
	public void getClassPage(ClassContainer cc, PairedUserContainer sc,
			SecurityToken st, boolean parent) {

		// Get homework
		// The array is in the same order as the class array, so the ith entry
		// in one
		// corresponds to the ith entry in the other
		// This could potentially contain a lot of information. Should the
		// architecture
		// be changed so that homework is looked up as needed?
		HomeworkContainer studentHomework[] = SchoolDBSQL.getSchoolDBSQL(
				(String) st.getValue(FormFields.SCHOOLNAME))
				.loadStudentClassHomework(
				// schoolName).loadStudentClassHomework(
						cc.getClassAssignedID());
		GradeContainer studentGrade[] = new GradeContainer[studentHomework.length];

		if (parent) {
			// st.putValue("childContainer", new Student
			// Container(sc.getIDForClasses().toString()));
			st.putValue("childContainer", UserContainer.getUserContainer(sc
					.getIDForClasses().toString(), st.getValue(
					FormFields.SCHOOLNAME).toString()));
			// st.putValue("childContainer",
			// UserContainer.getUserContainer(sc.getIDForClasses().toString(),
			// schoolName));
		}

		for (int j = 0; j < studentHomework.length; j++) {
			studentGrade[j] = GradeContainer.getGradeContainer(
					studentHomework[j].getClassID().toString(),
					studentHomework[j].getHomeworkID().toString(), sc
							.getIDForClasses().toString(), st.getValue(
							FormFields.SCHOOLNAME).toString());
			// schoolName);
		}
		st.putValue("homeworkContainer", studentHomework);
		st.putValue("studentGrade", studentGrade);

		// Get communications and sender (teacher) info
		// The two arrays are synchronized so that the ith entry in one
		// corresponds to
		// the ith entry in the other
		// This is inefficient, since we may be storing (and querying) the same
		// sender's
		// information many times
		ContactContainer studentCommunications[] = SchoolDBSQL.getSchoolDBSQL(
				(String) st.getValue(FormFields.SCHOOLNAME)).loadContacts(
				// schoolName).loadContacts(
				sc.getAssignedID().toString(),
				cc.getClassAssignedID().toString());
		UserContainer teacherWhoSentMail[] = new UserContainer[studentCommunications.length];
		for (int i = 0; i < studentCommunications.length; i++) {
			teacherWhoSentMail[i] = UserContainer.getUserContainer(
					studentCommunications[i].getFromID().toString(), st
							.getValue(FormFields.SCHOOLNAME).toString());
			// schoolName);
		}
		st.putValue("communicationContainer", studentCommunications);
		st.putValue("teacherWhoSentMail", teacherWhoSentMail);
		st.putValue("studentGrade", studentGrade);
	}

	/**
	 * Loads all mail and homework for a class.
	 * 
	 * @param sc
	 *            The user container for which information is to be loaded.
	 * @param st
	 *            The token where information is to be stored.
	 * @param parent
	 *            Indicates whether the user is a parent (if not, then the user
	 *            is a student)
	 */
	public void getTodaysPage(PairedUserContainer sc, SecurityToken st,
			boolean parent) {

		// Get homework
		// The array is in the same order as the class array, so the ith entry
		// in one
		// corresponds to the ith entry in the other
		// This could potentially contain a lot of information. Should the
		// architecture
		// be changed so that homework is looked up as needed?
		HomeworkContainer studentHomework[] = SchoolDBSQL.getSchoolDBSQL(
				(String) st.getValue(FormFields.SCHOOLNAME))
				.loadTodaysHomework(sc.getStudentID());
		st.putValue("homeworkContainer", studentHomework);

		GradeContainer studentGrade[] = new GradeContainer[studentHomework.length];

		for (int j = 0; j < studentHomework.length; j++) {
			studentGrade[j] = GradeContainer.getGradeContainer(
					studentHomework[j].getClassID().toString(),
					studentHomework[j].getHomeworkID().toString(), sc
							.getIDForClasses().toString(), st.getValue(
							FormFields.SCHOOLNAME).toString());
		}

		if (parent) {
			st.putValue("childContainer", UserContainer.getUserContainer(sc
					.getIDForClasses().toString(), st.getValue(
					FormFields.SCHOOLNAME).toString()));
		}

		// Get communications and sender (teacher) info
		// The two arrays are synchronized so that the ith entry in one
		// corresponds to
		// the ith entry in the other
		// This is inefficient, since we may be storing (and querying) the same
		// sender's
		// information many times
		ContactContainer studentCommunications[] = SchoolDBSQL.getSchoolDBSQL(
				(String) st.getValue(FormFields.SCHOOLNAME))
				.loadTodaysContacts(sc.getAssignedID().toString());
		UserContainer teacherWhoSentMail[] = new UserContainer[studentCommunications.length];
		for (int i = 0; i < studentCommunications.length; i++) {
			teacherWhoSentMail[i] = UserContainer.getUserContainer(
					studentCommunications[i].getFromID().toString(), st
							.getValue(FormFields.SCHOOLNAME).toString());
		}
		st.putValue("communicationContainer", studentCommunications);
		st.putValue("teacherWhoSentMail", teacherWhoSentMail);
		st.putValue("studentGrade", studentGrade);
	}
}
